//
//  PPFanUserListViewController.m
//  pickpic
//
//  Created by GaoYongyue on 16/9/12.
//  Copyright © 2016年 MicroDream. All rights reserved.
//

#import "PPFanUserListViewController.h"
#import "PPFollowUserCell.h"
#import "PPNetworkService.h"
#import "PPFanModel.h"
#import "PPUser.h"
#import "PPProfileViewController.h"

static const NSInteger kCount = 50;
@interface PPFanUserListViewController ()<PPFollowUserCellDelegate>
@property (nonatomic, strong) NSNumber *next;
@end

@implementation PPFanUserListViewController
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"被关注";

    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PPFollowUserCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([PPFollowUserCell class])];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.items count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56.f;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPUser *user = [self.items safeObjectAtIndex:indexPath.row];

    PPFollowUserCell *userCell = (PPFollowUserCell *)cell;
    userCell.delegateViewController = self;
    userCell.user = user;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    PPFollowUserCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PPFollowUserCell class])];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    //进入个人主页
    PPUser *user = [self.items safeObjectAtIndex:indexPath.row];
    PPProfileViewController *profileViewConroller = [[PPProfileViewController alloc] init];
    profileViewConroller.userID = user.userID;
    [self.navigationController pushViewController:profileViewConroller animated:YES];
}

#pragma mark - Timeline
- (NSArray *)initialItems
{
    if ([_userID isEqual:@([DGCurrentAccount.userID integerValue])])
    {
        NSArray *localUsers = [PPFanModel where:[NSPredicate predicateWithFormat:@"currentUserID == %@", DGCurrentAccount.userID]];
        NSMutableArray *localItems = [[NSMutableArray alloc] init];
        [localUsers enumerateObjectsUsingBlock:^(PPFanModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            PPUser *user = [[PPUser alloc] init];
            user.userID = obj.userID;
            user.nick = obj.nick;
            user.signature = obj.signature;
            user.avatar = obj.avatar;
            user.relationship = obj.relationship;
            user.avatarHost = obj.avatarHost;

            [localItems addSafeObject:user];
        }];
        return localItems;
    }
    return nil;
}

- (void)fetchNewItems {
    [super fetchNewItems];

    _next = nil;
    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchFanListWithTargetUserID:_userID start:nil limit:kCount callback:^(id data, NSError *error){
        if (data)
        {
            [weakSelf didReceiveNewResult:data];
        }
        else
        {
            [weakSelf didReceiveNewResult:error];
        }
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchFanListWithTargetUserID:_userID start:nil limit:kCount callback:^(id data, NSError *error){
        if (data)
        {
            [weakSelf didReceiveMoreResult:data];
        }
        else
        {
            [weakSelf didReceiveMoreResult:error];
        }
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    NSArray *items = [super didReceiveNewResult:result];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}


- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    self.next = [[result validDictionary] validNumberForKey:@"next"];
    NSArray *users = [[result validDictionary] validArrayForKey:@"users"];
    [users enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PPUser *user = [[PPUser alloc] init];
        user.userID = [[obj validDictionary] validStringForKey:@"user"];
        user.nick = [[obj validDictionary] validStringForKey:@"name"];
        user.avatar = [[obj validDictionary] validStringForKey:@"avatar"];
        user.signature = [[obj validDictionary] validStringForKey:@"signature"];
        user.relationship = [[obj validDictionary] validNumberForKey:@"relationship"];
        user.avatarHost = [[obj validDictionary] validStringForKey:@"avatarHost"];

        [items addSafeObject:user];
    }];

    if ([_userID isEqual:@([DGCurrentAccount.userID integerValue])])
    {
        //缓存
        [PPFanModel performInBlock:^(NSManagedObjectContext *context) {
            [items enumerateObjectsUsingBlock:^(PPUser *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                PPFanModel *fanModel = [PPFanModel existingFanForUserID:obj.userID];
                fanModel.nick = obj.nick;
                fanModel.signature = obj.signature;
                fanModel.relationship = obj.relationship;
                fanModel.avatar = obj.avatar;
                fanModel.avatarHost = obj.avatarHost;
            }];

            [context saveContext];
        }];
    }

    return items;
}

- (void)clearItems
{
    if ([_userID isEqual:@([DGCurrentAccount.userID integerValue])])
    {
        [PPFanModel performInBlock:^(NSManagedObjectContext *context) {

            NSArray <PPFanModel *> *localItems = [PPFanModel where:[NSPredicate predicateWithFormat:@"currentUserID == %@", DGCurrentAccount.userID]];

            [localItems enumerateObjectsUsingBlock:^(PPFanModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [obj delete];
            }];
            
            [context saveContext];
        }];
    }
}

#pragma mark - PPFollowUserCellDelegate
- (void)userCell:(PPFollowUserCell *)cell user:(PPUser *)user relationShipDidChanged:(NSNumber *)relationship
{
    [PPFanModel performInBlock:^(NSManagedObjectContext *context) {
        PPFanModel *fanModel = [PPFanModel existingFanForUserID:user.userID];
        fanModel.relationship = relationship;

        [context saveContext];
    }];
}
@end
